using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Threading;
using System.Collections;
using EnterpriseDT.Net.Ftp;

namespace PicturePage
{
    public partial class Form1 : Form
    {
        private FTPConnection ftpConnection = new FTPConnection();
        private bool ftpSettingExist = false;
        private bool readyToRun = false;

        private Configuration config = new Configuration();

        public Form1()
        {
            InitializeComponent();

            ftpSettingExist = SetupSettings("config.xml");

            cboYear.Items.Add("1996");
            cboYear.Items.Add("1997");
            cboYear.Items.Add("1998");
            cboYear.Items.Add("1999");
            cboYear.Items.Add("2000");
            cboYear.Items.Add("2001");
            cboYear.Items.Add("2002");
            cboYear.Items.Add("2003");
            cboYear.Items.Add("2004");
            cboYear.Items.Add("2005");
            cboYear.Items.Add("2006");
            cboYear.Items.Add("2007");
            cboYear.Items.Add("2008");
            cboYear.Items.Add("2009");
            cboYear.Items.Add("2010");
            cboYear.Items.Add("2011");
            cboYear.Items.Add("2012");
            cboYear.Items.Add("2013");
            cboYear.Items.Add("2014");
            cboYear.Items.Add("2015");
            cboYear.Items.Add("2016");
            cboYear.SelectedItem = DateTime.Today.Year.ToString();

            cboWeek.Items.Add("Week 1");
            cboWeek.Items.Add("Week 2");
            cboWeek.Items.Add("Week 3");
            cboWeek.Items.Add("Week 4");
            cboWeek.Items.Add("Week 5");
            cboWeek.Items.Add("Teen Week");
            cboWeek.SelectedIndex = 0;

            txtOutputDirectory.Text = "C:\\Pictures\\";
        }

        /// <summary>
        /// Sets up the FTP Settings from an external file
        /// </summary>
        private bool SetupSettings(string filename)
        {
            if (File.Exists(filename))
            {
                config = Configuration.Deserialize("config.xml");

                if (config.ConfigPassword != "SomeStringThatNoOneWillEverUseDefault")
                {
                    //create a popup box that inputs a password...
                    PopupBox popupBox = new PopupBox();
                    popupBox.StartPosition = FormStartPosition.CenterScreen;
                    int tries = 3;
                    while (tries >= 0)
                    {
                        config.ConfigPassword = popupBox.ShowInputBox("Input Password", "Please Input your Password.");

                        //if they cancelled to closed the password window...
                        if (config.ConfigPassword == "SomeStringThatNoOneWillEverUse") { break; }

                        try
                        {
                            ftpConnection.ServerAddress = config.GetDecryptedServerAddress();
                            ftpConnection.ServerPort = config.GetDecryptedServerPort();
                            ftpConnection.UserName = config.GetDecryptedUserName();
                            ftpConnection.Password = config.GetDecryptedPassword();

                            MessageBox.Show("Password Correct!", "FTP Password", MessageBoxButtons.OK);
                            return true;
                        }
                        catch
                        {
                            MessageBox.Show("Password was not Correct!\r\n" + tries.ToString() + " attempts left", "FTP Password", MessageBoxButtons.OK);
                        }
                        tries--;
                    }
                }
                return false;
            }
            else
            {
                MessageBox.Show("No FTP Settings were found!", "No FTP Settings", MessageBoxButtons.OK);
                return false;
            }
        }

        /// <summary>
        /// Edits the label that tells the number of pictures
        /// </summary>
        /// <param name="add">True means Add, False means Subtract</param>
        private void EditPictureNumber(bool add)
        {
            int numberOfPictures = 0;
            int.TryParse(lblNumberOfPictures.Text, out numberOfPictures);
            if (add)
            {
                numberOfPictures++;
            }
            else
            {
                numberOfPictures--;
            }
            lblNumberOfPictures.Text = numberOfPictures.ToString();
        }
        
        /****************************** All of the button actions ******************************/
        /// <summary>
        /// Browses for the output directory
        /// </summary>
        private void btnBrowseDirectory_Click(object sender, EventArgs e)
        {
            if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
            {
                txtOutputDirectory.Text = folderBrowserDialog1.SelectedPath;
            }
        }


        /// <summary>
        /// Adds a picture to the list
        /// </summary>
        private void btnAdd_Click(object sender, EventArgs e)
        {
            openFileDialogPicture.Filter = "JPG, PNG|*.jpg;*.png";
            openFileDialogPicture.FileName = "";
            if (openFileDialogPicture.ShowDialog() == DialogResult.OK)
            {
                foreach (string pictureFile in openFileDialogPicture.FileNames)
                {
                    ListViewItem lvi = new ListViewItem();
                    lvi.Text = pictureFile.Substring(pictureFile.LastIndexOf("\\") + 1);
                    lvi.Name = pictureFile;
                    lvi.ToolTipText = pictureFile;
                    pictureListView.Items.Add(lvi);

                    EditPictureNumber(true);
                }
            }
        }

        /// <summary>
        /// Removes the selected pictures from the list
        /// </summary>
        private void btnRemove_Click(object sender, EventArgs e)
        {
            foreach (ListViewItem listViewItem in pictureListView.SelectedItems)
            {
                pictureListView.Items.Remove(listViewItem);
                EditPictureNumber(false);
            }
        }

        /// <summary>
        /// Event that happens when you click the cancel button, cancels the process
        /// </summary>
        private void btnCancel_Click(object sender, EventArgs e)
        {
            backgroundWorker1.CancelAsync();
            this.btnCancel.Enabled = false;
            WriteLine("Cancelling... Please wait for current action to complete.", 0);
        }

        /// <summary>
        /// The action that happens when you click on the start button
        /// </summary>
        private void btnStart_Click(object sender, EventArgs e)
        {
            DisableForm(false);
            progressBar.Minimum = 0;
            progressBar.Maximum = (pictureListView.Items.Count * 3) + (pictureListView.Items.Count / 12);
            progressBar.Step = 1;
            this.backgroundWorker1.RunWorkerAsync();
        }
        /****************************** End of the button actions ******************************/
        /***************************************************************************************/

        /****************************** Used for the main process ******************************/
        private void StartProcess(object sender, DoWorkEventArgs e)
        {
            WriteLine("Process Began.", 0);

            string outputDirectory = GetOuputDirectory();
            string yearItem = GetYearSelectedItem();
            string weekItem = GetWeekSelectedItem();
            string yearText = GetYearSelectedText();
            string weekText = GetWeekSelectedText();
            string albumName = GetAlbumName();

            string pictureDirectory = outputDirectory + "\\" + yearItem + "\\" + weekItem + "\\" + albumName + "\\";
            if (!Directory.Exists(pictureDirectory))
            {
                Directory.CreateDirectory(pictureDirectory);
                WriteLine("\tCreating Directory: " + pictureDirectory, 0);
            }
            WriteLine("\tCopying Images and Creating Thumbnails.", 0);
            int pictureCount = GetPictureCount(); //total number of pictures
            for (int i = 0; i < pictureCount; i++)
            {
                if (!backgroundWorker1.CancellationPending)
                {
                    string pictureText = GetPictureText(i);
                    string pictureName = GetPictureName(i);

                    WriteLine("\t\tCopying File: " + pictureText, 0);
                    WriteLine("\t\tCreating Thumbnail...", 0);

                    string imageFile = pictureDirectory + pictureText;
                    string thumbnail = imageFile.Insert(imageFile.Length - 4, "Thumbnail");

                    string[] parameters = new string[] { pictureName, imageFile, thumbnail };
                    Thread thread = new Thread(new ParameterizedThreadStart(CopyImages));
                    thread.Start((object)parameters);

                    UpdateProgress();
                }
            }
            WriteLine("\tDone Copying Images and Creating Thumbnails.", 0);
            WriteLine("\t-------------------------------------------------------", 0);

            // publichtml/images/campPictures/ALBUM HTML FILE
            // publichtml/images/campPictures/YEAR/WEEK/ALBUM/ALL THE PICTURES

            //the link to the pictures from the html page
            string pictureLink = yearItem + "/" + weekItem + "/" + albumName + "/";
            //html file name
            string htmlFile = albumName + weekText + yearText + "_";
            
            ArrayList htmlFileList = new ArrayList();
            int countPictures = 0;
            int numberOfPicOnPage = (int)(config.Rows * config.Columns); //number of pictures on a page
            int endFile = 1; //tracks the number of pictures on a page
            int numberOfPages = (int)System.Math.Ceiling((decimal)pictureCount / (decimal)numberOfPicOnPage);
            int pageNumber = 1;
            while (countPictures < pictureCount)
            {
                if (!backgroundWorker1.CancellationPending)
                {
                    //open the template file
                    StreamReader inFile = new StreamReader(config.TemplateFile);
                    //create the picture file
                    string outputFile = outputDirectory + "\\" + htmlFile + pageNumber.ToString() + ".html";
                    StreamWriter outFile = new StreamWriter(outputFile);
                    WriteLine("\tCreating html page: " + outputFile, 0);
                    htmlFileList.Add(outputFile);

                    //read through all the beginning of the file until we get to the rightColumn div
                    string readLine = "";
                    while (!inFile.EndOfStream && !readLine.Contains(config.TemplateInsertLocation))
                    {
                        readLine = inFile.ReadLine();
                        outFile.WriteLine(readLine);
                    }
                    outFile.WriteLine("\t\t\t\t<p align=\"" + config.PictureAlign + "\">");

                    //create the links at the top of the page to link to every other picture page
                    CreatePageLinks(outFile, htmlFile, numberOfPages, pageNumber);

                    //start the table to put the designated number of pictures in
                    outFile.WriteLine("\t\t\t\t<table>");
                    outFile.WriteLine("\t\t\t\t\t<tr>");
                    int counter = 1; //counter for number of pictures in each row (or number of columns)
                    while (endFile <= numberOfPicOnPage)
                    {
                        UpdateProgress();

                        outFile.WriteLine("\t\t\t\t\t\t<td width=\"220px\" height=\"155px\">");

                        string picture = GetPictureText(countPictures);
                        WriteLine("\t\tPutting picture on page: " + pictureLink + picture.Insert(picture.Length - 4, "Thumbnail"), 0);
                        string lineToWrite = "\t\t\t\t\t\t\t";
                        if (config.MakeLinkedImages)
                        {
                            lineToWrite += "<a href=\"" + pictureLink + picture + "\">";
                        }
                        lineToWrite += "<img src=\"" + pictureLink + picture.Insert(picture.Length - 4, "Thumbnail") + "\" width=\"" + config.ThumbnailWidth + "px\" height=\"" + config.ThumbnailHeight + "px\" />";
                        if (config.MakeLinkedImages)
                        {
                            lineToWrite += "</a>";
                        }
                        outFile.WriteLine(lineToWrite);
                        outFile.WriteLine("\t\t\t\t\t\t</td>");

                        if (counter == config.Columns)
                        {
                            counter = 1;
                            outFile.WriteLine("\t\t\t\t\t</tr>");
                            outFile.WriteLine("\t\t\t\t\t<tr>");
                        }
                        else
                        {
                            counter++;
                        }

                        endFile++;
                        countPictures++;
                        if (countPictures == pictureCount)
                        {
                            break;
                        }
                    }
                    endFile = 1;
                    outFile.WriteLine("\t\t\t\t\t</tr>");
                    outFile.WriteLine("\t\t\t\t</table>");

                    //put the same links that are at the top of the page at the bottom
                    CreatePageLinks(outFile, htmlFile, numberOfPages, pageNumber);
                    outFile.WriteLine("\t\t\t\t</p>");

                    //finish outputing the file
                    readLine = "";
                    while (!inFile.EndOfStream)
                    {
                        readLine = inFile.ReadLine();
                        outFile.WriteLine(readLine);
                    }

                    //close the files
                    inFile.Close();
                    outFile.Close();
                    WriteLine("\tSaving html page...", 0);

                    pageNumber++;
                }
            }

            WriteLine("Process Complete.\r\n", 0);

            if (ftpSettingExist)
            {
                //now that all the files have been created FTP them to the web server
                WriteLine("FTP Files.", 0);
                WriteLine("\tCreating Connection", 0);
                //for each file created above we need to upload it to website/ftpsite
                for (int i = 0; i < pictureCount; i++)
                {
                    if (!backgroundWorker1.CancellationPending)
                    {

                        string pictureName = GetPictureName(i);
                        string pictureText = GetPictureText(i);
                        UpdateProgress();
                        WriteLine("\tUploading picture: " + pictureName, 0);

                        object[] parameters = new object[] { pictureText, pictureDirectory, yearItem, weekItem, albumName, ftpConnection };
                        Thread thread = new Thread(new ParameterizedThreadStart(FTPImages));
                        thread.Start((object)parameters);
                        thread.Join();
                    }
                }
                WriteLine("\tPictures Uploaded", 0);
                foreach (string html in htmlFileList)
                {
                    if (!backgroundWorker1.CancellationPending)
                    {
                        ConnectToFTP(ftpConnection); //make sure we are connected
                        ftpConnection.UploadFile(html, html.Substring(html.LastIndexOf("\\") + 1)); //upload the html Files
                        UpdateProgress();
                        WriteLine("\tUploading HTML files", 0);
                    }
                }
                WriteLine("\tHTML Files Uploaded", 0);

                //download the file that will link to our newly created album
                WriteLine("\tTrying to add a link to the right page on the site.", 0);
                string serverPath = "Pictures" + yearItem + ".html";
                string localPath = outputDirectory + "PicturesEdit.html";
                string newLocalPath = outputDirectory + "Pictures.html";
                try
                {
                    WriteLine("\tDownloading the file", 0);
                    //File.Create(localPath);
                    ftpConnection.DownloadFile(localPath, serverPath);
                    WriteLine("\tFile Downloaded!", 0);
                }
                catch
                {
                    WriteLine("\tCould not download file", 0);
                    MessageBox.Show("Could not download the file. Process complete.", "Download File", MessageBoxButtons.OK);
                    return;
                }

                //open the downloaded file, read through it all and add the link in the right place
                bool linkAdded = false;
                StreamReader htmlInFile = new StreamReader(localPath);
                StreamWriter htmlOutFile = new StreamWriter(newLocalPath);
                while (!htmlInFile.EndOfStream)
                {
                    if (!backgroundWorker1.CancellationPending)
                    {

                        string readLine = htmlInFile.ReadLine();
                        if (readLine == "\t\t\t\t\t<h3>" + weekItem + "</h3><p>")
                        {
                            htmlOutFile.WriteLine(readLine);
                            htmlOutFile.WriteLine("\t\t\t\t\t\t<a href=\"" + htmlFile + "1.html\">" + albumName + "</a><br/>");
                            WriteLine("\tLink Added!", 0);
                            linkAdded = true;
                        }
                        else
                        {
                            htmlOutFile.WriteLine(readLine);
                        }
                    }
                }
                if (!linkAdded)
                {
                    WriteLine("\tCould not find the place to add the link to.", 0);
                    MessageBox.Show("Could not add the Link", "Link", MessageBoxButtons.OK);
                }
                //close the files and delete them
                htmlInFile.Close();
                File.Delete(localPath);
                htmlOutFile.Close();

                //upload the file to the ftpserver
                try
                {
                    ftpConnection.UploadFile(newLocalPath, serverPath);
                    WriteLine("\tFile Uploaded Back to the Server!", 0);
                }
                catch
                {
                    WriteLine("\tCould not Upload the File back to the server", 0);
                    MessageBox.Show("Could not Upload File", "Upload File", MessageBoxButtons.OK);
                }
                File.Delete(newLocalPath);

                WriteLine("FTP Complete.\r\n", 0);
            }
        }

        /// <summary>
        /// Fires when the background worker has finished (Conversion complete or cancelled by user)
        /// </summary>
        /// <param name="sender" type="object/BackgroundWorker">This is the backgroundworker</param>
        /// <param name="e" type="RunWorkerCompletedEventArgs">EventArgs after completion</param>
        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Cancelled)
                MessageBox.Show("Process Cancelled", "Process Cancelled", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            else
                MessageBox.Show("Process Complete.\r\nCheck Message and Email me!", "Done", MessageBoxButtons.OK, MessageBoxIcon.Information);

            PrintEndMessage();

            //re-enable the controls
            DisableForm(true);
        }
        
        /// <summary>
        /// Enables/Disables all of the form
        /// </summary>
        /// <param name="enable">True to enable and False to disable</param>
        private void DisableForm(bool enable)
        {
            txtOutputDirectory.Enabled = enable;
            txtAlbumName.Enabled = enable;
            cboWeek.Enabled = enable;
            cboYear.Enabled = enable;
            btnStart.Enabled = enable;
            btnRemove.Enabled = enable;
            btnAdd.Enabled = enable;
        }

        /// <summary>
        /// Copies all the images over resizing them if needed and creating Thumbnail images. Optimized for multi-threads.
        /// </summary>
        /// <param name="parameters" type="object">The original image, The path to copy the image to, The path to copy the thumbnail to</param>
        private void CopyImages(object parameters)
        {
            string[] newParameters = (string[])parameters;
            string original = (string)newParameters[0]; //original image
            string copy = (string)newParameters[1]; //path to new image
            string thumbnail = (string)newParameters[2]; //thumbnail image
            Image image = Image.FromFile(original);

            if (config.MakeLinkedImages)
            {
                Image copyImage = null;
                if (image.Width > config.LinkedImageWidth && image.Height > config.LinkedImageHeight)
                {
                    copyImage = image.GetThumbnailImage(config.LinkedImageWidth, config.LinkedImageHeight, new Image.GetThumbnailImageAbort(ThumbnailCallback), IntPtr.Zero);
                    copyImage.Save(copy);
                }
                else
                {
                    image.Save(copy);
                }
                if (copyImage != null)
                {
                    copyImage.Dispose();
                }
            }

            Image thumbnailImage = image.GetThumbnailImage(config.ThumbnailWidth, config.ThumbnailHeight, new Image.GetThumbnailImageAbort(ThumbnailCallback), IntPtr.Zero);
            thumbnailImage.Save(thumbnail);
            thumbnailImage.Dispose();
            image.Dispose();
        }

        /// <summary>
        /// Creates the links to the other picture pages at the top and bottom of each page
        /// </summary>
        /// <param name="numberOfPages">Number of total Pages</param>
        /// <param name="pageNumber">Current page number</param>
        /// <param name="writeLine">The line to output</param>
        private void CreatePageLinks(StreamWriter outFile, string htmlFile, int numberOfPages, int pageNumber)
        {
            string writeLine = "";
            int pages = 1;
            writeLine = "\t\t\t\t\t";
            while (pages <= numberOfPages)
            {
                if (pages == pageNumber)
                {
                    writeLine += pages.ToString() + " - ";
                }
                else
                {
                    writeLine += "<a href=\"" + htmlFile + pages.ToString() + ".html\">" + pages.ToString() + "</a> - ";
                }
                pages++;
            }
            writeLine = writeLine.Remove(writeLine.Length - 3);
            outFile.WriteLine(writeLine);
        }

        /// <summary>
        /// Copies all the images to the FTP server. Optimized for multi-threads.
        /// </summary>
        /// <param name="parameters" type="object">image file location, picture directory, year combo, week combo, album text box, ftp connection</param>
        private void FTPImages(object parameters)
        {
            object[] newParameters = (object[])parameters;
            string pictureFile = (string)newParameters[0]; //image file location
            string pictureDirectory = (string)newParameters[1]; //directory where the pictures are
            string year = (string)newParameters[2]; //year combo box
            string week = (string)newParameters[3]; //week combo box
            string album = (string)newParameters[4]; //album text box
            FTPConnection ftpConnection = (FTPConnection)newParameters[5]; //the ftp connection

            string imageFile = year + "/" + week + "/" + album;
            string thumbnail = imageFile + "/" + pictureFile.Insert(pictureFile.Length - 4, "Thumbnail");

            string localImageFile = pictureDirectory + pictureFile;
            string localThumbnail = localImageFile.Insert(localImageFile.Length - 4, "Thumbnail");

            ConnectToFTP(ftpConnection);
            CreateDirectory(imageFile, ftpConnection);

            ftpConnection.UploadFile(localImageFile, imageFile + "/" + pictureFile);
            ftpConnection.UploadFile(localThumbnail, thumbnail);
        }

        /// <summary>
        /// Connects to the ftp server if it needs to
        /// </summary>
        private void ConnectToFTP(FTPConnection ftpConnection)
        {
            //only make a new connection if there isn't already a connection
            if (!ftpConnection.IsConnected)
            {
                ftpConnection.Protocol = FileTransferProtocol.FTP;
                ftpConnection.Connect();
            }
        }

        /// <summary>
        /// Creates a directory on the ftp if it is needed
        /// </summary>
        /// <param name="directory"></param>
        /// <param name="ftpConnection"></param>
        private void CreateDirectory(string directory, FTPConnection ftpConnection)
        {
            string[] dir = directory.Split('/');
            string directoryToCheck = "";
            foreach (string checkDir in dir)
            {
                try
                {
                    bool createDirectory = true; //tells us if we need to create the directory
                    string[] ftpFiles = ftpConnection.GetFiles(directoryToCheck); //need all the files in that folder first
                    directoryToCheck += checkDir; //add the directory we are checking
                    foreach (string ftpFile in ftpFiles)
                    {
                        //if we find a match then we don't need to create the directory
                        if (ftpFile == directoryToCheck)
                        {
                            createDirectory = false;
                        }
                    }
                    directoryToCheck += "/"; //need to append this so the directory will get created properly
                    if (createDirectory)
                        ftpConnection.CreateDirectory(directoryToCheck); //create the directory
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }

        /// <summary>
        /// Used for the GetThumbnailImage Method
        /// </summary>
        private bool ThumbnailCallback()
        {
            return false;
        }

        /// <summary>
        /// This is the message that should be printed when everything is complete
        /// </summary>
        private void PrintEndMessage()
        {
            WriteLine("\r\n\r\n", 0);
            WriteLine("/***********************************************/", 0);
            WriteLine("* Please email me this information:\t*", 0);
            WriteLine("* My Email: carlowahlstedt@gmail.com\t*", 0);
            WriteLine("* Album Name: " + txtAlbumName.Text + "\t\t*", 0);
            WriteLine("* Year: " + cboYear.SelectedValue + "\t\t\t*", 0);
            WriteLine("* Week: " + cboWeek.SelectedValue + "\t\t\t*", 0);
            WriteLine("/**********************************************/", 0);
        }
        /************************* End of used for the main process *************************/
        /************************************************************************************/


        /*********************** Used to access the form from a thread ***********************/
        /// <summary>
        /// Used with the WriteLine method for accessing the text box across threads.
        /// </summary>
        public delegate void WriteLineDelegate(string text, int tabNumber);
        /// <summary>
        /// Prints the given text to the text box.
        /// </summary>
        /// <param name="text">The text</param>
        /// <param name="tabNumber">The number of tabs</param>
        public void WriteLine(string text, int tabNumber)
        {
            if (this.txtStatus.InvokeRequired && this != null)
            {
                this.Invoke(new WriteLineDelegate(WriteLine), new object[] { text, tabNumber });
            }
            else
            {
                StringBuilder sb = new StringBuilder();

                sb.Append('\t', tabNumber);
                sb.Append(text);
                sb.Append(Environment.NewLine);
                txtStatus.AppendText(sb.ToString());

                Refresh();
            }
        }

        private string GetOuputDirectory()
        {
            string output = null;
            this.txtOutputDirectory.Invoke((MethodInvoker)delegate()
            {
                output = txtOutputDirectory.Text;
            });
            return output;
        }

        private string GetYearSelectedItem()
        {
            string year = null;
            this.cboYear.Invoke((MethodInvoker)delegate()
            {
                year = this.cboYear.SelectedItem.ToString();
            });
            return year;
        }

        private string GetYearSelectedText()
        {
            string year = null;
            this.cboYear.Invoke((MethodInvoker)delegate()
            {
                year = this.cboYear.SelectedText;
            });
            return year;
        }

        private string GetWeekSelectedItem()
        {
            string week = null;
            this.cboWeek.Invoke((MethodInvoker)delegate()
            {
                week = cboWeek.SelectedItem.ToString();
            });
            return week;
        }

        private string GetWeekSelectedText()
        {
            string week = null;
            this.cboWeek.Invoke((MethodInvoker)delegate()
            {
                week = cboWeek.SelectedText;
            });
            return week;
        }

        private string GetAlbumName()
        {
            string albumName = null;
            this.txtAlbumName.Invoke((MethodInvoker)delegate()
            {
                albumName = this.txtAlbumName.Text;
            });
            return albumName;
        }

        private int GetPictureCount()
        {
            int count = 0;
            this.pictureListView.Invoke((MethodInvoker)delegate()
            {
                count = this.pictureListView.Items.Count;
            });
            return count;
        }

        private string GetPictureText(int picture)
        {
            string text = "";
            this.pictureListView.Invoke((MethodInvoker)delegate()
            {
                text = this.pictureListView.Items[picture].Text;
            });
            return text;
        }

        private string GetPictureName(int picture)
        {
            string name = "";
            this.pictureListView.Invoke((MethodInvoker)delegate()
            {
                name = this.pictureListView.Items[picture].Name;
            });
            return name;
        }

        /// <summary>
        /// Updates the progressBar on the worker thread
        /// </summary>
        private void UpdateProgress()
        {
            this.progressBar.Invoke((MethodInvoker)delegate()
            {
                progressBar.PerformStep();
            });
        }
        /********************** End of used to access the form from a thread **********************/
        /******************************************************************************************/


        /********************** This is everything for the menu **********************/
        /// <summary>
        /// The event that happens when you click on the ftp settings menu item
        /// </summary>
        private void fTPSettingsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FTPSettingsForm settingsForm = new FTPSettingsForm(config);

            DialogResult dialogResult = settingsForm.ShowDialog();
            if (dialogResult == DialogResult.OK)
            {
                MessageBox.Show("Settings Saved");
            }
        }

        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            About about = new About();
            about.ShowDialog();
        }

        private void templateSettingsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            TemplateSettings templateSettings = new TemplateSettings(config);
            templateSettings.ShowDialog();
        }

        private void pictureSettingsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            PictureSettings pictureSettings = new PictureSettings(config);
            pictureSettings.ShowDialog();
        }

        /********************** End of everything for the menu **********************/
        /****************************************************************************/
    }
}